﻿#region

using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Helpers;
using System.Web.Http;
using log4net;
using xConnected.Service;

#endregion

namespace xConnected.Web.Controllers
{
    public class UploadController : ApiController
    {
        private readonly CompanyProfileService _companyProfileService;
        private readonly PositionService _positionService;
        private readonly ExpertProfileService _profileService;
        private readonly UserService _userService;

        public UploadController(UserService userService, ExpertProfileService profileService,
                                CompanyProfileService companyProfileService, PositionService positionService)
        {
            _userService = userService;
            _profileService = profileService;
            _companyProfileService = companyProfileService;
            _positionService = positionService;
        }

        [System.Web.Mvc.HttpPost]
        public HttpResponseMessage UploadCompanyPhoto(HttpPostedFileBase file, int companyId)
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                var user = _userService.GetUserByUsername(User.Identity.Name);
                var company = _companyProfileService.GetById(companyId);
                //if the profile belongs to current user save changes
                if (company.UserId == user.Id)
                {
                    var username = user.Username;
                    var directory =
                        HttpContext.Current.Server.MapPath("~/Content/Uploads/" +
                                                           Path.Combine(username, "CompanyProfiles",
                                                                        companyId.ToString(), "Photo"));
                    var dir = new DirectoryInfo(directory);
                    if (!dir.Exists)
                        dir.Create();

                    var filePath = Path.Combine(directory, file.FileName);
                    File.WriteAllBytes(filePath, ReadData(file.InputStream));
                    var image = new WebImage(filePath);
                    image.Resize(250, 250, true, false);
                    image.Save(Path.Combine(directory, "250X250_" + file.FileName));
                    image.Resize(150, 150, true, false);
                    image.Save(Path.Combine(directory, "150X150_" + file.FileName));
                    image.Resize(80, 80, true, false);
                    image.Save(Path.Combine(directory, "80X80_" + file.FileName));
                    image.Resize(50, 50, true, false);
                    image.Save(Path.Combine(directory, "50X50_" + file.FileName));
                    var path = "../../Content/Uploads/" + username + "/" + "CompanyProfiles" + "/" +
                               companyId.ToString() + "/" + "Photo" + "/" + "250X250_" + file.FileName;

                    var response = Request.CreateResponse(HttpStatusCode.OK, path);
                    return response;
                }
                //else if the profile doesn't belong to current user return "error" 
                //which means to render "you are not allowed...." message on client side
                return new HttpResponseMessage(HttpStatusCode.Forbidden);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                throw new HttpResponseException(HttpStatusCode.NotImplemented);
            }
        }

        [System.Web.Mvc.HttpPost]
        public HttpResponseMessage PostExpertPhoto(HttpPostedFileBase file, int profileId)
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                var user = _userService.GetUserByUsername(User.Identity.Name);
                var expert = _profileService.GetById(profileId);
                //if the profile belongs to current user save changes
                if (expert.UserId == user.Id)
                {
                    var username = user.Username;
                    var directory =
                        HttpContext.Current.Server.MapPath("~/Content/Uploads/" +
                                                           Path.Combine(username, "ExpertProfiles", profileId.ToString(),
                                                                        "Photo"));
                    var dir = new DirectoryInfo(directory);
                    if (!dir.Exists)
                        dir.Create();

                    var filePath = Path.Combine(directory, file.FileName);
                    File.WriteAllBytes(filePath, ReadData(file.InputStream));
                    var image = new WebImage(filePath);
                    image.Resize(250, 250, true, false);
                    image.Save(Path.Combine(directory, "250X250_" + file.FileName));
                    image.Resize(150, 150, true, false);
                    image.Save(Path.Combine(directory, "150X150_" + file.FileName));
                    image.Resize(80, 80, true, false);
                    image.Save(Path.Combine(directory, "80X80_" + file.FileName));
                    image.Resize(50, 50, true, false);
                    image.Save(Path.Combine(directory, "50X50_" + file.FileName));
                    var path = "../../Content/Uploads/" + username + "/" + "ExpertProfiles" + "/" + profileId.ToString() +
                               "/" + "Photo" + "/" + "250X250_" + file.FileName;

                    var response = Request.CreateResponse(HttpStatusCode.OK, path);
                    return response;
                }
                //else if the profile doesn't belong to current user return "error" 
                //which means to render "you are not allowed...." message on client side
                return new HttpResponseMessage(HttpStatusCode.Forbidden);
            }

            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                throw new HttpResponseException(HttpStatusCode.NotImplemented);
            }
        }

        [System.Web.Mvc.HttpPost]
        public HttpResponseMessage UploadProjectPhoto(HttpPostedFileBase file, int projectId)
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                var user = _userService.GetUserByUsername(User.Identity.Name);
                var position = _positionService.GetById(projectId);
                //if the profile belongs to current user save changes
                if (position.CompanyProfile.UserId == user.Id)
                {
                    var username = user.Username;
                    var directory =
                        HttpContext.Current.Server.MapPath("~/Content/Uploads/" +
                                                           Path.Combine(username, "ProjectProfiles",
                                                                        projectId.ToString(), "Photo"));
                    var dir = new DirectoryInfo(directory);
                    if (!dir.Exists)
                        dir.Create();

                    var filePath = Path.Combine(directory, file.FileName);
                    File.WriteAllBytes(filePath, ReadData(file.InputStream));
                    var image = new WebImage(filePath);
                    image.Resize(250, 250, true, false);
                    image.Save(Path.Combine(directory, "250X250_" + file.FileName));
                    image.Resize(150, 150, true, false);
                    image.Save(Path.Combine(directory, "150X150_" + file.FileName));
                    image.Resize(80, 80, true, false);
                    image.Save(Path.Combine(directory, "80X80_" + file.FileName));
                    image.Resize(50, 50, true, false);
                    image.Save(Path.Combine(directory, "50X50_" + file.FileName));
                    var path = "../../Content/Uploads/" + username + "/" + "ProjectProfiles" + "/" +
                               projectId.ToString() + "/" + "Photo" + "/" + "250X250_" + file.FileName;

                    var response = Request.CreateResponse(HttpStatusCode.OK, path);
                    return response;
                }
                //else if the profile doesn't belong to current user return "error" 
                //which means to render "you are not allowed...." message on client side
                return new HttpResponseMessage(HttpStatusCode.Forbidden);
            }

            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                throw new HttpResponseException(HttpStatusCode.NotImplemented);
            }
        }

        [System.Web.Mvc.HttpPost]
        public HttpResponseMessage UploadCv(HttpPostedFileBase file, int profileId)
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                var user = _userService.GetUserByUsername(User.Identity.Name);
                var expert = _profileService.GetById(profileId);
                //if the profile belongs to current user save changes
                if (expert.UserId == user.Id)
                {
                    var username = user.Username;
                    var directoryName =
                        HttpContext.Current.Server.MapPath("~/Content/Uploads/" +
                                                           Path.Combine(username, "ExpertProfiles", profileId.ToString(),
                                                                        "Cv"));
                    var di = new DirectoryInfo(directoryName);
                    if (!di.Exists)
                        di.Create();

                    // delete first all existing files
                    foreach (var fi in di.GetFiles())
                    {
                        fi.Delete();
                    }
                    var filePath = Path.Combine(directoryName, "Cv_" + file.FileName);
                    File.WriteAllBytes(filePath, ReadData(file.InputStream));
                    var path = "../../Content/Uploads/" + username + "/" + "ExpertProfiles" + "/" + profileId.ToString() +
                               "/" + "Cv" + "/" + "Cv_" + file.FileName;

                    var response = Request.CreateResponse(HttpStatusCode.OK, path);
                    return response;
                }
                //else if the profile doesn't belong to current user return "error" 
                //which means to render "you are not allowed...." message on client side
                return new HttpResponseMessage(HttpStatusCode.Forbidden);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                throw new HttpResponseException(HttpStatusCode.NotImplemented);
            }
        }

        private byte[] ReadData(Stream stream)
        {
            byte[] buffer = new byte[16*1024];

            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }

                return ms.ToArray();
            }
        }
    }
}